package com.example.user_registration.controller;

import com.example.user_registration.model.User;
import com.example.user_registration.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import jakarta.validation.Valid;

@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/")
    public String home() {
        return "redirect:/user/register";
    }

    @GetMapping("/user/register")
    public String showRegistrationForm(Model model) {
        model.addAttribute("user", new User());
        return "register";
    }

    @PostMapping("/register")
    public String registerUser(@Valid User user, BindingResult result, Model model) {
        if (result.hasErrors()) {
            // 如果有验证错误，返回注册页面
            return "register";
        }

        if (!userService.registerUser(user)) {
            model.addAttribute("error", "该邮箱已被注册");
            return "register";
        }
        
        model.addAttribute("success", "注册成功");
        return "register"; // 注册成功后返回注册页面
    }
}

